package bb.lanxing.activity.login

import android.content.Intent
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import bb.lanxing.App
import bb.lanxing.MainActivity
import bb.lanxing.R
import bb.lanxing.activity.interfaces.IGetAuthCodeView
import bb.lanxing.common.config.Constants.INTERVAL_1_MIN
import bb.lanxing.common.config.Constants.INTERVAL_1_SEC
import bb.lanxing.databinding.ActivityLogoutDirectionBinding
import bb.lanxing.lib.devices.base.DeviceContext
import bb.lanxing.lib.devices.core.utils.DeviceHelper
import bb.lanxing.manager.RemoteServiceManager
import bb.lanxing.manager.SharedManager
import bb.lanxing.model.database.LitePalTableBase
import bb.lanxing.model.database.RouteBook
import bb.lanxing.model.database.RouteBookInfo
import bb.lanxing.model.database.RouteBookPoint
import bb.lanxing.mvp.presetner.GetAuthCodePresenterImpl
import bb.lanxing.mvp.presetner.i.IGetAuthCodePresenter
import bb.lanxing.mvvm.base.BaseDBActivity
import bb.lanxing.network.MyHttpClient
import bb.lanxing.network.NetSubscribe
import bb.lanxing.util.Log
import bb.lanxing.util.Validator
import bb.lanxing.util.text.TextUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import rx.Observable
import rx.Observer
import rx.schedulers.Schedulers
import kotlin.jvm.internal.Intrinsics

class LogoutDirectionActivity : BaseDBActivity<ActivityLogoutDirectionBinding>(), IGetAuthCodeView {
    private lateinit var edt_authcode: EditText
    private lateinit var img_del_authcode: ImageView
    private lateinit var getAuthcodeBtn: TextView
    private lateinit var phone: String
    private var mTimer: CountDownTimer? = null
    private lateinit var presenter: IGetAuthCodePresenter

    override fun getLayoutId(): Int {
        return R.layout.activity_logout_direction
    }

    override fun initView(binding: ActivityLogoutDirectionBinding) {
        presenter = GetAuthCodePresenterImpl(this)
        phone = App.getContext().userPhone
        val root = binding.root
        edt_authcode = root.findViewById(R.id.edt_authcode)
        getAuthcodeBtn = root.findViewById(R.id.getAuthcodeBtn)
        img_del_authcode = root.findViewById(R.id.img_del_authcode)
        img_del_authcode.setOnClickListener { it ->
            delete(it, edt_authcode)
        }
        edt_authcode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmptyOrNull(s)) {
                    img_del_authcode.visibility = View.VISIBLE
                } else {
                    img_del_authcode.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }
        })
        getAuthcodeBtn.setOnClickListener(this::getAuthCodeBtnClick)
        setTitle(R.string.logout)
        setupActionBar(true)
        binding.btnNext.setOnClickListener(this::logout)
    }

    private fun logout(view: View) {
        if (RemoteServiceManager.getInstance().isSporting) {
            App.getContext().showMessage(R.string.mine_history_toast_stop_sport_first)
        } else {
            requestLogoutCheck()
        }
    }

    private fun requestLogoutCheck() {
        val authCode = edt_authcode.text.toString()
        if (TextUtils.isEmptyOrNull(authCode)) {
            ToastUtils.showShort(R.string.mine_login_get_message_code)
            return
        }
        showLoadingDialog(R.string.logout, false)
        Observable.create(NetSubscribe(MyHttpClient.unRegister(phone, authCode.toInt())))
            .subscribeOn(Schedulers.io()).observeOn(
                Schedulers.io()
            ).subscribe(object : Observer<String?> {
                override fun onCompleted() {}

                override fun onError(e: Throwable) {
                    Intrinsics.checkNotNullParameter(e, "e")
                    App.getContext().showMessage(e.message)
                    dismissLoadingDialog()
                }

                override fun onNext(str: String?) {
                    deleteData()
                }
            })
    }

    fun getAuthCodeBtnClick(view: View) {
        if (Validator.isPhoneNumber(phone)) {
            getAuthcodeBtn.isEnabled = false
            startCountDown()
            presenter.getAuthCode(phone, 0, 0)
            return
        }
        App.getContext().showMessage(R.string.mine_profile_phone_not_valid)
    }

    private fun delete(view: View, editText: EditText) {
        editText.setText("")
        view.visibility = View.GONE
    }

    private fun startCountDown() {
        mTimer = object : CountDownTimer(INTERVAL_1_MIN, INTERVAL_1_SEC) {
            override fun onTick(j: Long) {
                getAuthcodeBtn.text = getString(
                    R.string.mine_profile_get_auth_code_time, (j / 1000).toString()
                )
            }

            override fun onFinish() {
                getAuthcodeBtn.setText(R.string.mine_login_get_message_code)
                getAuthcodeBtn.isEnabled = true
            }
        }.start()
    }

    override fun onGetAuthCodeResult(result: Boolean, type: Int) {
        if (result) {
            startCountDown()
        }
    }

    override fun onGetAuthCodeResult(jsonObject: JSONObject) {
    }

    private fun deleteData() {
        lifecycleScope.launch() {
            withContext(Dispatchers.IO) {
                deleteDatabase()
            }
            cleanState()
            dismissLoadingDialog()
            goHomePage()
        }
    }

    private suspend fun deleteDatabase() {
        val userId = App.getContext().userId
        Log.i("deleteDatabase oldList userId = $userId")
        val oldList = RouteBook.getList()
        oldList.forEach {
            Log.i("deleteDatabase oldList it = ${it.userId}")
        }
        val userIdList = oldList.filter { routeBook -> userId == routeBook.userId }.toList()
        userIdList.forEach { item ->
            LitePalTableBase.deleteAll(
                RouteBookInfo::class.java, "serverId = ?", item.serverId.toString()
            )
            LitePalTableBase.deleteAll(
                RouteBookPoint::class.java, "lushuId = ?", item.id.toString()
            )
        }
        val userIdStr = userId.toString()
        LitePalTableBase.deleteAll(
            RouteBook::class.java, "userId = ?", userIdStr
        )
    }

    private fun cleanState() {
        App.getContext().cleanSigninState()
        SharedManager.getInstance().userPhone = ""
        App.getContext().showMessage(R.string.st_logout_account_success)
        sendMessage(R.id.msg_user_logout)
        DeviceContext.stopAutoConnector()
        DeviceHelper.disconnectAll()
    }

    private fun goHomePage() {
        val intent = Intent()
        intent.setClass(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
}
